#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pytesseract
import requests
from PIL import Image
from lxml import etree

# 封装验证码识别
def getCodeText(imgPath):
    image = Image.open(imgPath)
    randCode = pytesseract.image_to_string(image)
    return randCode


if __name__ == "__main__":
    host = "https://so.gushiwen.cn/"
    # 爬取到页面源码数据
    url = host + '/user/login.aspx?from=http://so.gushiwen.cn/user/collect.aspx'
    # UA伪装
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.42'
    }
    page_text = requests.get(url=url, headers=headers).text
    # 解析验证码图片的 src
    tree = etree.HTML(page_text)
    code_img_src = host + tree.xpath('//*[@id="imgCode"]/@src')[0]
    img_data = requests.get(url=code_img_src, headers=headers).content
    # 将验证码图片保存到了本地
    with open('data/code.jpg', 'wb') as fp:
        fp.write(img_data)
    # 调用 ocr 进行图片识别
    code_text = getCodeText('data/code.jpg')
    print(code_text)

